Background

This is the model for the lower reach of a small, turbulent, shaded stream with a fair amount of fine particulate organic matter, Glenbrook Creek NV, USA.

Identifying reasonable modeled estimates of K600

We then ran normal pooling on k600 in stream metabolizer model: b_Kb_oipi_tr_plrckm.stan to get modeled K600 to see if we could resolve the negative correlation between ER and K600. Priors on K600_lnQ_nodes_meanlog were set as 5 bins based on rnorm(1000, mean = logQ_mean, sd = logQ_sd) centered around the mean and logQ values 1-2 sd away from the mean.

Load metab data from different model segments with normal prior for gas exchange.

We chose segments of time where we believe GPP occurred and was greater than 0. These chunks of time are from a previous model where we binned flow and incorporated measured and estimated K600 priors from gas exchange measurements a the reach.

Metabolism with CIs for the full time series

This the raw model output. It looks like there are many days with fitting issues. Where GPP is in blue and ER is in orange.

Here is the run configuration for full model:

mm_name(type = 'bayes', pool_K600 = "binned", err_obs_iid = TRUE, err_proc_iid = TRUE, ode_method = "trapezoid", deficit_src = 'DO_mod', engine = 'stan')

Fitting priors:

K600_lnQ_nodes_meanlog = log(25) Where 25 was the mean value from observed measurements and normal pooled modeled, K600_lnQ_nodes_sdlog = 1.1 was 1.1, bayes_specs_new$K600_lnQ_nodes_centers <- log_bins was from prior_samples <- rnorm(1000, mean = logQ_mean, sd = logQ_sd) based on mean discharge for all flows > 0.99 cms to cut off some extreme values.

Checking full model convergence

Make sure the chains converged; all r-hat values were well below 1.05 (the red line) for GPP, ER, and K600. The blue lines are the mean for each parameter.

k600.rhat <- mean(na.omit(met.full$K600_daily_Rhat))
k600.rhat
## [1] 1.013708
GPP.rhat <- mean(na.omit(met.full$GPP_Rhat))
GPP.rhat
## [1] 1.001413
ER.rhat <- mean(na.omit(met.full$ER_Rhat))
ER.rhat
## [1] 1.012106
# Create a dataframe for the vertical lines
rhat_lines <- data.frame(
  Param = c("K600_daily_Rhat", "GPP_daily_Rhat", "ER_daily_Rhat"),
  yintercept = c(k600.rhat, GPP.rhat, ER.rhat)
)

met.full %>%
  select(date, GPP_daily_Rhat, ER_daily_Rhat, K600_daily_Rhat) %>%
  pivot_longer(2:4, values_to = "Rhat", names_to = "Param") %>%
  ggplot(aes(x = date, y = Rhat), col=lab) +
  geom_hline(yintercept = 1.05, col = "red", lty = 2) + 
  geom_point(size = 0.5, alpha = 0.5) +
  geom_hline(data = rhat_lines, aes(yintercept = yintercept), col = "blue", lty = 2) + 
  theme_classic() +
  facet_wrap(~Param, ncol = 3)

In general convergence looks alright, but there are still many days with unrealistic GPP or ER.

##       date                lab                 rmse              sd          
##  Min.   :2021-03-13   Length:1912        Min.   :0.0088   Min.   :0.004922  
##  1st Qu.:2022-02-17   Class :character   1st Qu.:0.0364   1st Qu.:0.139621  
##  Median :2023-04-17   Mode  :character   Median :0.0550   Median :0.235482  
##  Mean   :2023-01-30                      Mean   :0.1008   Mean   :0.276757  
##  3rd Qu.:2024-01-24                      3rd Qu.:0.1094   3rd Qu.:0.367734  
##  Max.   :2024-10-08                      Max.   :0.9391   Max.   :1.070590  
##                                          NA's   :506                        
##       min              max             range             nrmse       
##  Min.   : 3.755   Min.   : 5.535   Min.   :0.01333   Min.   :0.0133  
##  1st Qu.: 6.796   1st Qu.: 7.567   1st Qu.:0.46592   1st Qu.:0.0466  
##  Median : 7.747   Median : 8.687   Median :0.73883   Median :0.0769  
##  Mean   : 7.702   Mean   : 8.578   Mean   :0.87562   Mean   :0.0935  
##  3rd Qu.: 9.064   3rd Qu.: 9.717   3rd Qu.:1.15217   3rd Qu.:0.1274  
##  Max.   :10.061   Max.   :11.395   Max.   :3.37000   Max.   :0.3636  
##                                                      NA's   :506     
##       minT             maxT            rangeT              minQ          
##  Min.   : 1.000   Min.   : 1.015   Min.   :0.007333   Min.   :0.0006898  
##  1st Qu.: 1.808   1st Qu.: 3.979   1st Qu.:1.653750   1st Qu.:0.0071279  
##  Median : 6.000   Median : 9.627   Median :2.533833   Median :0.0167851  
##  Mean   : 5.876   Mean   : 8.688   Mean   :2.811335   Mean   :0.0424491  
##  3rd Qu.: 9.369   3rd Qu.:12.758   3rd Qu.:3.742500   3rd Qu.:0.0338001  
##  Max.   :13.870   Max.   :16.380   Max.   :7.573333   Max.   :0.6346135  
##                                                                          
##       maxQ               rangeQ        
##  Min.   :0.0009197   Min.   :0.000000  
##  1st Qu.:0.0108068   1st Qu.:0.002529  
##  Median :0.0243728   Median :0.005978  
##  Mean   :0.0609296   Mean   :0.018481  
##  3rd Qu.:0.0506618   3rd Qu.:0.016613  
##  Max.   :0.7764051   Max.   :0.393798  
## 

Looking at the estimated K600 and ER relationships from normal pooling

Here is the run configuration to get modeled K600:

mm_name(type = 'bayes', pool_K600 = "normal", err_obs_iid = TRUE, err_proc_iid = TRUE, ode_method = "trapezoid", deficit_src = 'DO_mod', engine = 'stan')

Where each “lab” segment was run as individual model with the K600_lnQ_nodes_meanlog adjusted to match streamline in cms during that time.

Compared modeled and measured K600

Plots for (1) measured v modeled K600 and flow and (2) logK600 and log(flow+1).

Could be one poor measurement at the highest flow for measured gas exchange. But in general the modeled K600 does seem similar to the measured, which is kind of nice to see how robust the pool_K600 = "normal" is getting at K600.

Full run with binned K600 informed by both measured and modeled priors

Here is the run configuration for full model:

mm_name(type = 'bayes', pool_K600 = "binned", err_obs_iid = TRUE, err_proc_iid = TRUE, ode_method = "trapezoid", deficit_src = 'DO_mod', engine = 'stan')

Quick plot of flow bins given flow range:

Where dashed vertical lines correspond to the prior locations for flow bins in bayes_specs_new$K600_lnQ_nodes_centers <- log_bins

dat1 <- input_dat%>% filter(discharge<0.99) 
## Set bayes specs
bayes_name_new <- mm_name(type = 'bayes', pool_K600 = "binned",
                          err_obs_iid = TRUE, err_proc_iid = TRUE,
                          ode_method = "trapezoid", deficit_src = 'DO_mod', engine = 'stan')
bayes_specs_new <- specs(bayes_name_new)

# Compute log-transformed discharge
logQ <- log(na.omit(dat1$discharge))
sd_logQ <- round(sd(na.omit(logQ)),2)


## Compute log-transformed K600 for prior estimation
logQ_mean <- round(mean(logQ, na.rm = TRUE),2)  # Center the prior flow mean
logQ_mean
## [1] -3.96
logQ_sd <- round(c(sd(logQ, na.rm = TRUE)),1)  # Double the SD for a wider prior
logQ_sd
## [1] 1.3
logK600_mean <- round(log(25),1)  # Center the prior on mean k600
logK600_mean
## [1] 3.2
logK600_sd <- round(c(log(75/25)),2)  # Double the SD for a wider prior
logK600_sd
## [1] 1.1
range_prior_U <- exp(logK600_mean +logK600_sd)
range_prior_U
## [1] 73.69979
range_prior_L <- exp(logK600_mean -logK600_sd)
range_prior_L
## [1] 8.16617
prior_samples <- rnorm(1000, mean = logQ_mean, sd = logQ_sd)
# Define bins based on log-scale mean and SD
log_bins <- c(logQ_mean - c(2 * logQ_sd), 
              logQ_mean - c(1 * logQ_sd), 
              logQ_mean, 
              logQ_mean + c(1 * logQ_sd), 
              logQ_mean + c(2 * logQ_sd))

# Plot:
#bins <- exp(log_bins)
prior_df <- data.frame(Q_cms = prior_samples)
prior_bins_plot <- ggplot(prior_df, aes(x = Q_cms)) +
  geom_density(fill = "lightblue", alpha = 0.5) +  # Density plot
  geom_vline(xintercept = log_bins, color = "black", lty="dashed") +  # Bin edges
  labs(title = "Binned log(flow) for K600 Priors", y = "Density", x = "log(Q) (cms)") +
  theme_bw()
prior_bins_plot

# Assign priors for binned K600
bayes_specs_new$K600_lnQ_nodes_meanlog <- rep(logK600_mean, length(log_bins))  # Centered at 25
bayes_specs_new$K600_lnQ_nodes_meanlog
## [1] 3.2 3.2 3.2 3.2 3.2
bayes_specs_new$K600_lnQ_nodes_sdlog <- rep(logK600_sd, length(log_bins))  # Wide enough to allow 40
bayes_specs_new$K600_lnQ_nodes_sdlog 
## [1] 1.1 1.1 1.1 1.1 1.1
bayes_specs_new$K600_lnQ_nodes_centers <- log_bins
bayes_specs_new$K600_lnQ_nodes_centers
## [1] -6.56 -5.26 -3.96 -2.66 -1.36
# Keep other parameters
bayes_specs_new$K600_daily_sigma_sigma <- 0.05 

bayes_specs_new$n_chains <- c(3)
bayes_specs_new$n_cores <- c(3)
bayes_specs_new$burnin_steps <- c(2500)
bayes_specs_new$saved_steps <- c(2500)

bayes_specs_new
## Model specifications:
##   model_name               b_Kb_oipi_tr_plrckm.stan                             
##   engine                   stan                                                 
##   split_dates              FALSE                                                
##   keep_mcmcs               TRUE                                                 
##   keep_mcmc_data           TRUE                                                 
##   day_start                4                                                    
##   day_end                  28                                                   
##   day_tests                full_day, even_timesteps, complete_data, pos_disch...
##   required_timestep        NA                                                   
##   K600_lnQ_nodes_centers   -6.56, -5.26, -3.96, -2.66, -1.36                    
##   GPP_daily_mu             3.1                                                  
##   GPP_daily_lower          -Inf                                                 
##   GPP_daily_sigma          6                                                    
##   ER_daily_mu              -7.1                                                 
##   ER_daily_upper           Inf                                                  
##   ER_daily_sigma           7.1                                                  
##   K600_lnQ_nodediffs_sdlog 0.5                                                  
##   K600_lnQ_nodes_meanlog   3.2, 3.2, 3.2, 3.2, 3.2                              
##   K600_lnQ_nodes_sdlog     1.1, 1.1, 1.1, 1.1, 1.1                              
##   K600_daily_sigma_sigma   0.05                                                 
##   err_obs_iid_sigma_scale  0.03                                                 
##   err_proc_iid_sigma_scale 5                                                    
##   params_in                GPP_daily_mu, GPP_daily_lower, GPP_daily_sigma, ER...
##   params_out               GPP, ER, DO_R2, GPP_daily, ER_daily, K600_daily, K...
##   n_chains                 3                                                    
##   n_cores                  3                                                    
##   burnin_steps             2500                                                 
##   saved_steps              2500                                                 
##   thin_steps               1                                                    
##   verbose                  FALSE

Plots made on filtered data: met.clean filtered for days with GPP_daily_Rhat<1.05,ER_daily_Rhat<1.05, K600_daily_Rhat <1.05, as well as (GPP_97.5pct>0) and (ER_2.5pct<0).

met.clean <- met.full %>%
  filter(GPP_daily_Rhat<1.05)%>%
  filter(GPP_97.5pct>0)%>%
  filter(ER_daily_Rhat<1.05) %>%
  filter(ER_2.5pct<0)%>%
  filter(K600_daily_Rhat<1.05)

mean_k_mod <- mean(met.clean$K600_daily_mean)
mean_k_mod
## [1] 16.93494
mean_k_measure <- mean(measured_K$K600)
mean_k_measure
## [1] 39.53105
KER_cor <- round(cor(met.clean$ER_daily_mean, met.clean$K600_daily_mean, use = "complete.obs"),3)
print(KER_cor)
## [1] -0.759
KGPP_cor <-round(cor(met.clean$GPP_daily_mean, met.clean$K600_daily_mean, use = "complete.obs"),3)
print(KGPP_cor)
## [1] 0.073

The vertical dashed is the overall mean modeled K600 in the box plot.

GPP and ER

## [1] -0.091

Final thoughts.

The direction of the K600 ~ flow relationship looks more logical, where K600 increases with flow. ER and K600 are still very negatively correlated (-0.759) but it might just mean that ER is not an identifiable parameter in this reach.

The mean modeled K600 is lower than expected, 16.9 when it should be closer to 25. Overall this could just be a challenging reach to fit the model to.

Final cleaned model output:

Where GPP is in blue and ER is in orange, and the black points represent NEP.

Table summarizing excluded data from cleaned model output:

Table summarizing excluded data from cleaned model output:

Number of Days Explaination Percent of Days
1037 Total days of DO observations 100.0
699 Total days removed 67.4
0 Days with high flow 0.0
334 Days model was unable to fit 32.2
0 days where GPP rhat > 1.05 0.0
0 days where ER rhat > 1.05 0.0
0 days where K600 rhat > 1.05 0.0
365 days where modeled GPP was negative 35.2
5 days where modeled ER was positive 0.5
26 days with clean GPP fits >= 0 2.7
620 days with clean ER fits <= 0 64.9

Session info

R version 4.4.2 (2024-10-31)

Platform: aarch64-apple-darwin20

locale: en_US.UTF-8||en_US.UTF-8||en_US.UTF-8||C||en_US.UTF-8||en_US.UTF-8

attached base packages: stats, graphics, grDevices, utils, datasets, methods and base

other attached packages: plotly(v.4.10.4), kableExtra(v.1.4.0), knitr(v.1.49), streamMetabolizer(v.0.12.1), ggpubr(v.0.6.0), readxl(v.1.4.3), zoo(v.1.8-12), cowplot(v.1.1.3), viridis(v.0.6.5), viridisLite(v.0.4.2), dataRetrieval(v.2.7.17), lubridate(v.1.9.4), forcats(v.1.0.0), stringr(v.1.5.1), dplyr(v.1.1.4), purrr(v.1.0.4), readr(v.2.1.5), tidyr(v.1.3.1), tibble(v.3.2.1), ggplot2(v.3.5.1) and tidyverse(v.2.0.0)

loaded via a namespace (and not attached): DBI(v.1.2.3), gridExtra(v.2.3), rlang(v.1.1.5), magrittr(v.2.0.3), e1071(v.1.7-16), compiler(v.4.4.2), mgcv(v.1.9-1), systemfonts(v.1.1.0), vctrs(v.0.6.5), pkgconfig(v.2.0.3), crayon(v.1.5.3), fastmap(v.1.2.0), backports(v.1.5.0), labeling(v.0.4.3), pander(v.0.6.5), deSolve(v.1.40), rmarkdown(v.2.29), tzdb(v.0.4.0), bit(v.4.5.0.1), xfun(v.0.49), cachem(v.1.1.0), jsonlite(v.1.9.1), broom(v.1.0.7), parallel(v.4.4.2), R6(v.2.6.1), bslib(v.0.8.0), stringi(v.1.8.4), car(v.3.1-3), jquerylib(v.0.1.4), cellranger(v.1.1.0), Rcpp(v.1.0.14), Matrix(v.1.7-1), splines(v.4.4.2), timechange(v.0.3.0), tidyselect(v.1.2.1), rstudioapi(v.0.17.1), abind(v.1.4-8), yaml(v.2.3.10), lattice(v.0.22-6), plyr(v.1.8.9), withr(v.3.0.2), evaluate(v.1.0.1), rLakeAnalyzer(v.1.11.4.1), sf(v.1.0-19), units(v.0.8-5), proxy(v.0.4-27), xml2(v.1.3.6), pillar(v.1.10.1), carData(v.3.0-5), KernSmooth(v.2.23-24), generics(v.0.1.3), vroom(v.1.6.5), hms(v.1.1.3), munsell(v.0.5.1), scales(v.1.3.0), class(v.7.3-22), glue(v.1.8.0), lazyeval(v.0.2.2), tools(v.4.4.2), data.table(v.1.16.4), ggsignif(v.0.6.4), LakeMetabolizer(v.1.5.5), grid(v.4.4.2), crosstalk(v.1.2.1), colorspace(v.2.1-1), nlme(v.3.1-166), Formula(v.1.2-5), cli(v.3.6.4), svglite(v.2.1.3), gtable(v.0.3.6), rstatix(v.0.7.2), sass(v.0.4.9), digest(v.0.6.37), classInt(v.0.4-11), htmlwidgets(v.1.6.4), farver(v.2.1.2), htmltools(v.0.5.8.1), lifecycle(v.1.0.4), httr(v.1.4.7), unitted(v.0.2.9) and bit64(v.4.5.2)